import * as vscode from 'vscode';
import * as WebRequest from 'web-request';


function _translate(b: boolean) {
    const editor: vscode.TextEditor | undefined = vscode.window.activeTextEditor;
    if (!editor) {
        return;
    }
    let selection = editor.selection;
    let keyword = editor.document.getText(selection);

    // 获取选中的文本
    let url = "http://translate.googleapis.com/translate_a/single?client=gtx&dt=t&dj=1&ie=UTF-8&sl=auto&tl=zh-EN&q=";
    if (keyword) {
        url = url + encodeURI(keyword);
        WebRequest.get(url).then(resp => {
            let rep = JSON.parse(resp.content);
            let sentences = rep.sentences;
            if (sentences.length <= 0) {
                vscode.window.showErrorMessage("翻译失败：" + keyword);
                return;
            }
            var trans = sentences[0].trans;
            trans = underlineToCamel(trans);
            if (trans === "") {
                vscode.window.showErrorMessage("翻译失败：" + keyword);
                return;
            }

            var fname = editor.document.fileName
            fname = fname.substring(fname.lastIndexOf("\\") + 1, fname.lastIndexOf("."));

            var code =
                `/**
* ${keyword}
*/
${fname}.func.${trans} = function () {


}

             
`;
            editor.edit(editBuilder => {

                if (b) {
                    editBuilder.replace(selection, trans + ": function(){ },  //" + keyword);
                    const end = new vscode.Position(editor.document.lineCount + 1, 0);
                    editBuilder.replace(new vscode.Range(end, end), code);
                    vscode.window.showInformationMessage("生成成功 " + trans + ": function(){ }");
                } else {
                    vscode.window.showInformationMessage(keyword + "    <--翻译-->  " + trans);
                    editBuilder.replace(selection, trans);
                }
            });

        });
    } else {
        vscode.window.showErrorMessage("翻译失败");
    }
}

function underlineToCamel(param: string) {
    if ((param === null) || ("" === (param.trim()))) {
        return "";
    }
    var len = param.length;
    var str = "";
    for (var i = 0; i < len; i++) {
        let c = param.charAt(i);
        if (c === ' ') {
            i++;
            if (i < len) {
                str += param.charAt(i).toUpperCase();
            }
        }
        else {
            str += c.toLowerCase();
        }
    }
    return str;
}

export default {
    _translate: _translate
};